class Score < ActiveRecord::Base
  belongs_to :department
  belongs_to :user
  belongs_to :bus_type
  belongs_to :term_type

  #validates :acct_name, presence: true
  #validates :id_type, presence: true
  #validates :id_no, presence: true
  #validates :phone, presence: true
  validates :bus_type, presence: true
  #validates :acct_type, presence: true
  #validates :acct_no, presence: true
  #validates :create_date, presence: true
  #validates :amount, presence: true
  validates :term_type, presence: true
  validates :stan, presence: true
  validates :freeze_date, presence: true

  before_save :set_score

  def set_score
    if self.amount > 500000
      self.score = 60 * 50 + ((self.amount - 500000) / 10000 * 70)
    else
      if self.term_type == 2
        self.score = self.amount / 10000 * 60
      elsif self.term_type == 1
        self.score = self.amount / 10000 * 30
      else
        self.score = self.amount / 10000 * 15
      end
    end
  end

  ransacker :create_date, type: :date do
    Arel.sql('date(create_date)')
  end

  ransacker :create_date_casted do |parent|
    Arel::Nodes::NamedFunction.new("date", Arel::Nodes::SqlLiteral.new('create_date'))
  end

  scope :by_department, ->(dpid) do
    unless dpid.nil? || dpid.blank?
      dep = Department.find(dpid)
      if dep.level == 2
        where('departments.id in (?) or departments.id = ?', Department.select(:id).where(master_id: dep.id), dep.id)
      elsif dep.level == 3
        where('departments.id = ?', dep.id)
      end
    end
  end

  scope :by_user, ->(user) do
    #if user.department.level == 1
    #  where('1 = 1')
    #elsif user.department.level == 2
    if user.department.level == 2
      where("department_id in (?) or department_id = ?", Department.select(:id).where(master_id: user.department_id), user.department_id)
    elsif user.department.level == 3
      where(user_id: user.id)
    end
  end

  scope :count_by_user, ->(user, dpid) do
    if user.department.level == 1
      unless dpid.nil? || dpid.blank?
        by_department(dpid).group("departments.id")
      else
        group("departments.master_id")
      end
    elsif user.department.level == 2
      where("departments.master_id = ? or departments.id = ?", user.department_id, user.department_id)
        .group("departments.id")
    elsif user.department.level == 3
      where("departments.id = ?", user.department_id)
        .group(:id_type)
    end
  end



  def by_user11(user)
    if user.department.level == 1
      all
    elsif user.department.level == 2
      where(department_id: Department.select(:id).where(master_id: user.department_id))
    #  @scores = Score.joins(:department).where('departments.master_id = ?', current_user.department.id)
    else
      where(user_id: user.id)
    end
  end

  private

  def self.ransackable_scopes(obj = nil)
    %i(by_department)
  end
end
